package com.mtons.mblog.web.controller.site.document;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import com.mtons.mblog.base.lang.Result;
import com.mtons.mblog.modules.entity.DocumentQuestion;
import com.mtons.mblog.modules.service.DocumentQuestionService;
import com.mtons.mblog.web.controller.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Controller
@RequestMapping("/question")
public class DocumentQuestionController extends BaseController {

    @Autowired
    private DocumentQuestionService documentQuestionService;

    @PostMapping("/add")
    @ResponseBody
    public Result add(@RequestBody DocumentQuestion documentQuestion) {
        documentQuestionService.add(documentQuestion);
        return Result.successMessage("增加" + documentQuestion.getTitle() + "成功");
    }

    @RequestMapping("/search")
    public String search(String kw, ModelMap model) {
        Pageable pageable = wrapPageable();
        try {
            if (StringUtils.isNotEmpty(kw)) {
                Page<DocumentQuestion> page = documentQuestionService.search(pageable, kw);
                model.put("results", page);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.put("kw", kw);
        return view("/doc/result");
    }

    @RequestMapping("/reset")
    @ResponseBody
    public Result resetIndexes() {
        documentQuestionService.resetIndexes();
        return Result.success();
    }

    @RequestMapping("/init")
    @ResponseBody
    public Result txtImport() {
        String location = System.getProperty("site.location");
        File file = FileUtil.file(location, "init.txt");
        if (file.exists()) {
            BufferedReader utf8Reader = FileUtil.getUtf8Reader(file);
            List<DocumentQuestion> dList = new ArrayList<>();
            DocumentQuestion documentQuestion = null;
            int flag = 0;
            int seq;
            String title;
            StringBuffer contentBuffer = null;
            try {
                String lineContent;
                while ((lineContent = utf8Reader.readLine()) != null) {
                    //开头
                    if (lineContent.contains("单选") && flag == 0) {
                        documentQuestion = new DocumentQuestion();
                        String[] strArr = lineContent.split("单选");
                        seq = Integer.valueOf(strArr[0].trim());
                        title = lineContent.substring(strArr[0].length(), lineContent.length() - 1);
                        documentQuestion.setSeq(seq);
                        documentQuestion.setTitle(title);
                        contentBuffer = new StringBuffer();
                        flag = 1;
                    } else if (lineContent.contains("多选") && flag == 0) {
                        documentQuestion = new DocumentQuestion();
                        String[] strArr = lineContent.split("多选");
                        seq = Integer.valueOf(strArr[0].trim());
                        title = lineContent.substring(strArr[0].length(), lineContent.length() - 1);
                        documentQuestion.setSeq(seq);
                        documentQuestion.setTitle(title);
                        contentBuffer = new StringBuffer();
                        flag = 1;
                    } else if (lineContent.contains("判断") && flag == 0) {
                        documentQuestion = new DocumentQuestion();
                        String[] strArr = lineContent.split("判断");
                        seq = Integer.valueOf(strArr[0].trim());
                        title = lineContent.substring(strArr[0].length(), lineContent.length() - 1);
                        documentQuestion.setSeq(seq);
                        documentQuestion.setTitle(title);
                        contentBuffer = new StringBuffer();
                        flag = 1;
                    } else if (lineContent.contains("答案") && flag == 1) {
                        contentBuffer.append(lineContent);
                        documentQuestion.setContent(contentBuffer.toString());
                        dList.add(documentQuestion);
                        flag = 0;
                    } else if (flag == 1) {
                        contentBuffer.append(lineContent);
                        contentBuffer.append("<br>");
                    }
                }
            } catch (IOException e) {
                log.error("读取报错", e);
                return Result.failure("读取报错:" + e.getMessage());
            } finally {
                try {
                    utf8Reader.close();
                } catch (IOException e) {
                    log.error("关闭报错", e);
                }
            }
            if (CollectionUtil.isNotEmpty(dList)) {
                dList.forEach(vo -> {
                    try {
                        documentQuestionService.add(vo);
                    } catch (Exception ex) {
                        log.error("保存数据报错，编号:" + vo.getSeq(), ex);
                    }

                });
                return Result.successMessage("共新增：" + dList.size() + "条数据");
            }
        }
        return Result.success();
    }
}
